package com.hksj.Intelligentmanagement.auth.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.hksj.Intelligentmanagement.auth.dto.UserDTO;
import com.hksj.Intelligentmanagement.auth.entity.InitUser;
import com.hksj.Intelligentmanagement.auth.entity.User;
import com.hksj.Intelligentmanagement.auth.entity.UserRole;
import com.hksj.Intelligentmanagement.auth.mapper.UserMapper;
import com.hksj.Intelligentmanagement.auth.vo.UserVo;
import com.hksj.Intelligentmanagement.utils.RSAUtils;
import lombok.extern.slf4j.Slf4j;
import org.dozer.Mapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.PostConstruct;
import java.util.List;


/**
 * @ClassName UserService
 * @Description TODO
 * @Author @陈章
 * @Date 2023/2/20 14:14
 * @Version 1.0
 */

@Slf4j
@Service
public class UserService extends ServiceImpl<UserMapper, User> {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private Mapper mapper;
    @Autowired
    private Gson gson;
    @Autowired
    private InitUser initUser;
    @Value("${rsa.private}")
    private String privateSecurity;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    private UserRoleService userRoleService;

    //初始化管理员用户
    @PostConstruct
    public void initUser() {
        User user = new User();
        user.setUsername(initUser.getUsername());
        BCryptPasswordEncoder bCryptPasswordEncoder=new BCryptPasswordEncoder();
        //初始化的用户密码加密
        String encode = bCryptPasswordEncoder.encode(initUser.getPassword());
        user.setPassword(encode);
        user.setNickName(initUser.getUsername());
        user.setSex("2");
        //用户类型（0管理员，1普通用户
        user.setUserType("0");
        if (!exist(user.getUsername())) {
            userMapper.insert(user);
        }
    }


    public boolean exist(String username) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(User::getUsername, username);
        User one = super.getOne(wrapper);
        return one != null;
    }

    public void insert(UserDTO userDTO) {
        User userEntity = mapper.map(userDTO, User.class);
        String decrypt = RSAUtils.decrypt(userEntity.getPassword(), privateSecurity);
        userEntity.setPassword(passwordEncoder.encode(decrypt));
        userMapper.insert(userEntity);
        log.info(gson.toJson(userEntity));
    }

    public void del(String id) {
        //用户类型为0的不让删除
        User user = userMapper.selectById(id);
        if (!ObjectUtils.isEmpty(user) && "0".equals(user.getUserType())){
            throw new RuntimeException("管理员账号无法删除！");
        }
        //逻辑删除
        userMapper.deleteById(id);
        //删除用户关联角色
        LambdaQueryWrapper<UserRole> query = new QueryWrapper<UserRole>().lambda();
        query.eq(UserRole::getUserId,user.getId());
        userRoleService.remove(query);
    }

    public IPage<UserVo> findAll(String status,String username,Integer pageNum,Integer pageSize) {
        Page<UserVo> page = new Page<>(pageNum, pageSize);
        List<UserVo> userList = userMapper.selectUserList(page,status,username);
        page.setRecords(userList);
        return page;
    }

    public void updateUser(UserDTO userDTO) {
        User user = new User();
        BeanUtils.copyProperties(userDTO,user);
        userMapper.updateById(user);
    }
}